//
//  AlfrescoAppDelegate.m
//  Alfresco
//
//  Created by Michael Muller on 9/1/09.
//  Copyright Zia Consulting 2010.  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
//

#import "AlfrescoAppDelegate.h"
#import "RootViewController.h"
#import "SiteListDownload.h"
#import "Site.h"

@implementation AlfrescoAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize tabBarController;
@synthesize sitesController;

#pragma mark -
#pragma mark Application lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	[window addSubview:[tabBarController view]];
    [window makeKeyAndVisible];
	
	NSString *hostname = [[NSUserDefaults standardUserDefaults] stringForKey:@"host"];
	if (hostname == nil || [hostname isEqualToString:@"demo.ziaconsulting.com"]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Using Default Settings" message:@"Fresh docs is using a demonstration repository.\n\nTo access your own repository, you should configure it in the iPhone settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	}
	
	if (hostname == nil) {
		[self registerDefaultsFromSettingsBundle];
	}
}

// this works around the fact the settings return nil rather than the default if the user has never opened the preferences
// thank you "PCheese": http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the-s
- (void)registerDefaultsFromSettingsBundle {
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");
        return;
    }
	
    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
	
    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
    for (NSDictionary *prefSpecification in preferences) {
        NSString *key = [prefSpecification objectForKey:@"Key"];
        if (key) {
            [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
        }
    }
	
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
    [defaultsToRegister release];
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[navigationController release];
	[tabBarController release];
	[window release];
	[sitesController release];
	[super dealloc];
}


@end

